package com.yoomiito.app.utils

import android.view.View
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import java.util.concurrent.TimeUnit

class DebounceHelper {

    companion object{
        private val ob: Observable<Int> by lazy {
            Observable.just(1)
        }

        var listener:()->Unit={}
        /**
         * 对View的点击事件在设定的时间内进行防止二次点击，不带View参数的回调
         * @param view
         * @param debounceTime 设定的这个时间内，View点击只有一次起效，时间单位是秒
         * @param runnable  View的点击后的执行方法的回调
         */
        fun click(view: View,debounceTime:Long,runnable: Runnable){
            Observable.create<View> {
                var emitter = it
                view?.setOnClickListener {
                    emitter.onNext(it)
                }
            }.throttleFirst(debounceTime,TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe { runnable.run() }
        }

        /**
         * 对View的点击事件在设定的时间内进行防止二次点击，带View参数的回调
         * @param view
         * @param debounceTime 设定的这个时间内，View点击只有一次起效，时间单位是秒
         * @param listener  View的点击事件回调，带有本身View的参数
         */
        fun click(view: View,debounceTime:Long,listener:View.OnClickListener){
            Observable.create<View> {
                var emitter = it
                view?.setOnClickListener {
                    emitter.onNext(it)
                }
            }.throttleFirst(debounceTime, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe { listener.onClick(it) }
        }

        fun click(debounceTime:Long): Observable<Int> = ob.throttleFirst(debounceTime, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
    }
}